import {
  CheckboxCheckedChangeDetails,
  Checkmark,
  TreeCollection,
  TreeView,
  useTreeViewNodeContext,
} from "@chakra-ui/react";
import { LuFile, LuFolder } from "react-icons/lu";
import { IoChevronForward } from "react-icons/io5";
import { Box } from "@chakra-ui/react";

interface Node {
  id: string;
  name: string;
  children?: Node[];
  path?: string;
}

interface TreeViewCheckBoxProps {
  nodes: TreeCollection<Node> | null;
  // ✅ 新增：接收选中变化的回调
  onCheckedChange?: (checkedNodes: Node[]) => void;
}

function TreeNodeCheckbox(props: TreeView.NodeCheckboxProps) {
  const nodeState = useTreeViewNodeContext();

  return (
    <TreeView.NodeCheckbox aria-label="check node" {...props}>
      <Checkmark
        sm={{
          bg: nodeState.checked
            ? "darkcyan"
            : nodeState.checked === "indeterminate"
            ? "orange.500"
            : "gray.200",
          color: "white",
          borderRadius: "sm",
        }}
        size="sm"
        checked={nodeState.checked === true}
        indeterminate={nodeState.checked === "indeterminate"}
      />
    </TreeView.NodeCheckbox>
  );
}

function TreeViewCheckBox({ nodes, onCheckedChange }: TreeViewCheckBoxProps) {
  if (!nodes) {
    return <div>加载中...</div>;
  }

  // ✅ 将 checkedValue (id 列表) 转为 Node 对象列表
  const handleCheckedChange = (checkedValue: CheckboxCheckedChangeDetails) => {
    const checkedNodes: Node[] = [];
    // 遍历所有节点，找出被勾选的
    const visit = (node: TreeCollection<Node>) => {
      if (checkedValue.checkedValue.includes(node.id)) {
        checkedNodes.push(node?.path);
      }
      if (node.children) {
        node.children.forEach(visit);
      }
    };

    visit(nodes.rootNode);

    // ✅ 回调给父组件
    onCheckedChange?.(checkedNodes);
  };

  return (
    <TreeView.Root
      collection={nodes}
      maxW="sm"
      minW="240px"
      defaultCheckedValue={[]}
      onCheckedChange={handleCheckedChange} // ✅ 监听勾选变化
    >
      <TreeView.Label>脚本列表</TreeView.Label>
      <TreeView.Tree>
        <TreeView.Node
          render={({ node, nodeState }) => {
            const isExpanded = nodeState.isExpanded;

            return nodeState.isBranch ? (
              <TreeView.BranchControl role="none">
                {/* 手动箭头 */}
                <Box
                  as={IoChevronForward}
                  color="gray.500"
                  transition="transform 0.2s"
                  transform={isExpanded ? "rotate(90deg)" : "rotate(0deg)"}
                  fontSize="12px"
                  mr="1"
                />
                <TreeNodeCheckbox />
                <LuFolder />
                <TreeView.BranchText>{node.name}</TreeView.BranchText>
              </TreeView.BranchControl>
            ) : (
              <TreeView.Item>
                <TreeNodeCheckbox />
                <LuFile />
                <TreeView.ItemText>{node.name}</TreeView.ItemText>
              </TreeView.Item>
            );
          }}
        />
      </TreeView.Tree>
    </TreeView.Root>
  );
}

export default TreeViewCheckBox;